package com.common.allCommon;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONObjecthelper {
	
	private static final String TAG = "JSONObjecthelper";

	public static String getString(JSONObject json ,String name){
		if(json==null) return "";
		if(json.has(name)){
			try {
				return json.getString(name);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	/*
	 * 过滤null
	 */
	public static String getFilterString(JSONObject json ,String name){
		if(json==null) return "";
		if(json.has(name)){
			try {
				if(json.get(name)==JSONObject.NULL||json.isNull(name)){
					return "";
				}
				return json.getString(name);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	
	/**
	 * Key值不存或数据错误传回0值
	 * @param json
	 * @param name
	 * @return
	 */
	public static int getInt(JSONObject json ,String name){
		if(json==null) return 0;
		if(json.has(name)){
			try {
				String str = json.getString(name);
				if(str==null||"".equals(str))return 0;
				else{
					//用正则表达式判断字符串是不为数字
					if(RegexUtils.isNumeric(str)){
						return json.getInt(name);
					}
					else return 0;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	/**
	 * Key值不存或数据错误传回0值
	 * @param json
	 * @param name
	 * @return
	 */
	public static long getLong(JSONObject json ,String name){
		if(json==null) return 0;
		if(json.has(name)){
			try {
				String str = json.getString(name);
				if(str==null||"".equals(str))return 0;
				else{
					//用正则表达式判断字符串是不为数字
					if(RegexUtils.isNumeric(str)){
						return json.getLong(name);
					}
					else return 0;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	
	
	public static JSONArray getJSONArray(JSONObject json ,String name){
//		Log.v(TAG,"getJSONArray");
		JSONArray jsonArray = null;
		if(json==null) return jsonArray;
		if(json.has(name)){
			try {
//				Log.v(TAG,json.toString());
				return json.getJSONArray(name);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static JSONObject getJSONObject(JSONObject json ,String name){
		if(json==null) return null;
		if(json.has(name)){
			try {
				return json.getJSONObject(name);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static void putString(JSONObject json ,String name,String value) throws JSONException{		
		if(json==null||value==null||"".equals(value)) return;
		else json.put(name, value);		
	}	
	
	
	public static JSONObject getJSONObject(JSONArray jsonarray ,int i){
		JSONObject json = null;
		if(jsonarray==null) return json;
		if(jsonarray.length()<i){
			return json;
		}
		
		try {
			json = jsonarray.getJSONObject(i);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json;
	}
}
